const express = require('express');
const http = require('http');

class Server {
  constructor(options) {
    this.options = options;
    this.httpServer = null;
  }

  async listen(){
    const app = this.app = express();
    //使用一个静态文件中间件 用来让客户端可以访问staticDir里的文件
    app.use(express.static(this.options.staticDir));
    this.httpServer = http.createServer(app); //之所以要手动通过http.createServer, 是方便我们后面调用.close (app.listen后貌似无法关闭

    return new Promise(resolve => {
      this.httpServer?.listen(this.options.port, () => {
        console.log(`服务器已经在${this.options.port}端口上启动了`);
        resolve();
      });
    });
  }

  async close(){
    return new Promise(resolve => {
      console.log('准备关闭--- ---');
      console.log('this.httpServer.close:',this.httpServer.close);
      this.httpServer?.close(this.options.port, () => {
        console.log(`${this.options.port}端口已经关闭了`);
        resolve()
      });
    })
  }
}

module.exports = Server;
